﻿using System;
using System.Text;

namespace Lab620.WcfRadiusService.Clutch
{
    static class ReversePapAuth
    {
        public static string Reverse(byte[] sharedSecret, byte[] rqAuthenticator, byte[] requestPassword)
        {
            var passwordBuffLength = requestPassword.Length;
            var authData = new byte[16];
            var currentPasswordBlock = new byte[16];

            var outPasswordBuffer = new byte[requestPassword.Length];
            var passwordBlocks = passwordBuffLength/16;

            Buffer.BlockCopy(rqAuthenticator, 0, authData, 0, 16);

            for (var i = 0; i < passwordBlocks; i++)
            {
                Buffer.BlockCopy(requestPassword, i*16, currentPasswordBlock, 0, 16);

                PapAuthenticator.PAPEncryptBlock(sharedSecret, authData, currentPasswordBlock);

                Buffer.BlockCopy(currentPasswordBlock, i*16, outPasswordBuffer, 0, 16);

                Buffer.BlockCopy(currentPasswordBlock, 0, authData, 0, 16);
            }

            var outPassword = Encoding.ASCII.GetString(outPasswordBuffer).TrimEnd('\0');
            return outPassword;
        }
    }
}
